<?php

class Service_search extends MY_Service
{
    public function __construct()
    {
        parent::__construct();
        $this->load->driver('cache');
        $this->load->model('Model_urls');
        $this->load->model('Model_search');
        $this->load->library('EmojiUtil');
    }

    public function add($key, $ip)
    {
        $key = urldecode($key);
        if (empty($key) || !preg_match('/^[\\w\x{4e00}-\x{9fa5}]+$/u', $key)) {
            return false;
        }

        $data = [
            'key' => $key,
            'ip' => $ip
        ];
        $this->Model_search->insert($data);
    }

    public function getList($key, $page = 1, $size = 40)
    {
        $key = urldecode($key);
        if (empty($key) || !preg_match('/^[\\w\x{4e00}-\x{9fa5}]+$/u', $key)) {
            return [];
        }

        $mcKey = "search_" . md5($key);
        $result = $this->cache->memcached->get($mcKey);
        if (!empty($result)) {
            return $result;
        }

        $cond = [
            'title like ' => '%' . $key . '%',
            'or' => [
                'remark like ' => '%' . $key . '%'
            ]
        ];
        $result = $this->Model_urls->getList($page, $cond, $size);
        foreach ($result as $key => &$item) {
            if ($item['status'] != 0 || $item['show'] != 1) {
                unset($result[$key]);
                continue;
            }
            $item['url'] = '/site/index/' . $item['id'] . '.html';
            $item['title'] = EmojiUtil::utfToEmoji($item['title']);
            $item['remark'] = EmojiUtil::utfToEmoji($item['remark']);
        }
        $this->cache->memcached->save($mcKey, $result, 300);
        return $result;
    }

    public function getHot()
    {
        $mcKey = "mc_hot";
        $result = $this->cache->memcached->get($mcKey);
        if (!empty($result)) {
            return $result;
        }
        $sql = 'SELECT `key`, num FROM hot WHERE status = 0 ORDER BY num DESC';
        $result = $this->Model_search->query($sql);

        $this->cache->memcached->save($mcKey, $result, 300);
        return $result;
    }
}
